package com.study.crypto.general.spring.config;

import com.study.crypto.general.spring.interceptor.mybatis.GeneralEntityInterceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.boot.autoconfigure.MybatisAutoConfiguration;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

import java.util.List;

/**
 * @author Songjin
 * @since 2022-11-02 18:18
 */
@Configuration
@ConditionalOnClass(SqlSessionFactory.class)
@AutoConfigureAfter(MybatisAutoConfiguration.class)
@Lazy(false)
public class MyBatisPluginAutoConfiguration implements InitializingBean {

    @Autowired
    private List<SqlSessionFactory> sqlSessionFactories;

    @Override
    public void afterPropertiesSet() throws Exception {
        GeneralEntityInterceptor interceptor = new GeneralEntityInterceptor();
        for (SqlSessionFactory sqlSessionFactory : sqlSessionFactories) {
            org.apache.ibatis.session.Configuration configuration = sqlSessionFactory.getConfiguration();
            boolean contains = configuration.getInterceptors().contains(interceptor);
            if (!contains) {
                configuration.addInterceptor(interceptor);
            }
        }
    }
}
